<template>
  <el-drawer title="分类编辑" 
    v-model="drawer"
    size="800"
    @close="handleClose"
  >
    <ContentBody v-loading="store.updating">
      <el-form ref="refCategorForm"
        :model="categoryItem"
        :rules="rules"
        label-width="120px"
        style="width: 90%"
      >
        <el-form-item label="上级分类" prop="parentId" v-if="parentItem">
          <el-input v-model="parentItem.title" disabled />
        </el-form-item>
        <el-form-item label="分类名称" prop="title">
          <el-input v-model="categoryItem.title" placeholder="请填写分类名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </el-form-item>
      </el-form>
    </ContentBody>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter, useRoute } from 'vue-router'
import { useCategotryStore } from '@/stores/category'
import { ElMessage } from 'element-plus'

const drawer = ref(false)
const router = useRouter()
const route = useRoute()
const store = useCategotryStore()
const { parentItem, categoryItem } = storeToRefs(store)
const refCategorForm = ref()

const rules = {
  title: [
    {required: true, message: '请填写分类名称', trigger: 'blur'}
  ]
}

const handleSave = async () => {
  refCategorForm.value.validate(async(valid : boolean) => {
    if (valid) {
      const result = await store.saveCategory(categoryItem.value)
      if (result) {
        ElMessage.success('保存成功')
        router.back()
      } else {
        ElMessage.error('保存失败')
      }
    }
  })
}
const handleClose = () => {
  drawer.value = false
  router.back()
}

onMounted(() => {
  drawer.value = true
  if (route.params.id) {
    store.loadCategory(parseInt(route.params.id as string))
  } else {
    store.newCategory(parseInt(route.query.parentId as string))
  }
})
</script>